<template>
  <div class="emoji-grid">
    <div v-if="emojis.length === 0" class="empty-state">
      <el-empty description="暂无表情包" />
    </div>

    <div v-else class="grid-container">
      <div v-for="emoji in emojis" :key="emoji.id" class="emoji-card" @click="handleCopy(emoji)">

        <div class="emoji-actions">
          <el-button class="action-btn delete-btn" @click.stop="handleDelete(emoji)">
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </div>
        <div class="emoji-image">
          <img :src="emoji.type === 'url' ? emoji.url : emoji.data" :alt="emoji.name" loading="lazy" />

        </div>

        <div class="emoji-meta">
          <div class="emoji-info">
            <el-button :class="['favorite-btn', { 'is-favorite': emoji.favorite }]" @click.stop="handleFavorite(emoji)">
              <el-icon>
                <Star />
              </el-icon>
            </el-button>
            <div class="emoji-name">{{ emoji.name }}</div>
          </div>
          <div class="emoji-size">
            {{ formatSize(emoji.size) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { Delete, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useEmojiStore } from '../stores/emoji'

const props = defineProps({
  emojis: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['deleted'])

const emojiStore = useEmojiStore()

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 复制表情
const handleCopy = async (emoji) => {
  try {
    // 获取图片数据
    const response = await fetch(emoji.data)
    const blob = await response.blob()

    // 尝试使用navigator.clipboard.write
    try {
      const item = new ClipboardItem({
        [blob.type]: blob
      })
      await navigator.clipboard.write([item])
      ElMessage.success('复制图片成功')
    } catch (clipboardError) {
      console.error('clipboard.write失败，尝试其他方式:', clipboardError)

      // 如果clipboard.write失败，尝试使用canvas方式
      const img = new Image()
      img.src = emoji.data
      await new Promise((resolve) => {
        img.onload = resolve
      })

      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)

      canvas.toBlob(async (blob) => {
        try {
          const item = new ClipboardItem({
            [blob.type]: blob
          })
          await navigator.clipboard.write([item])
          ElMessage.success('复制图片成功')
        } catch (error) {
          console.error('canvas方式复制失败:', error)
          ElMessage.error('复制失败：' + error.message)
        }
      }, 'image/png')
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败：' + error.message)
  }
}

// 删除表情
const handleDelete = async (emoji) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个表情吗？删除后不可恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await emojiStore.deleteEmoji(emoji.id)
    ElMessage.success('删除成功')
    // 触发删除事件，通知父组件更新数据
    emit('deleted')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 收藏/取消收藏表情
const handleFavorite = async (emoji) => {
  try {
    await emojiStore.toggleFavorite(emoji.id)
    ElMessage.success(emoji.favorite ? '已取消收藏' : '已收藏')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}
</script>

<style lang="scss" scoped>
.emoji-grid {
  width: 100%;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 12px;
  padding: 12px 0;
}

.emoji-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 2;

  .delete-btn {
    width: 32px;
    height: 32px;
    right: 0;
    padding: 0;
    border-radius: 4px;
    background: white;
    border: 1px solid var(--el-color-danger);
    color: var(--el-color-danger);
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    :deep(.el-icon) {
      font-size: 16px;
    }

    &:hover {
      background: var(--el-color-danger);
      color: white;
    }
  }
}

.emoji-card {
  background: white;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .emoji-actions {
      opacity: 1;
      pointer-events: auto;
    }

    .emoji-image::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.03);
      pointer-events: none;
    }
  }

  .emoji-image {
    width: 100%;
    padding-top: 100%;
    position: relative;
    background: #f5f7fa;

    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
    }


  }

  .emoji-meta {
    padding: 8px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #ebeef5;
    background: #fafafa;

    .emoji-info {
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;

      .favorite-btn {
        width: 28px;
        height: 28px;
        padding: 0;
        border-radius: 4px;
        background: transparent;
        border: none;
        color: #606266;

        &:hover {
          color: #e6a23c;
        }

        &.is-favorite {
          color: #e6a23c;
        }
      }

      .emoji-name {
        font-size: 14px;
        color: #303133;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .emoji-size {
      font-size: 12px;
      color: #909399;
      white-space: nowrap;
      margin-left: 8px;
    }
  }
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}
</style>